//
//  Common.m
//  Zhiche-Carriage
//
//  Created by Code_浅蓝 on 17/4/18.
//  Copyright © 2017年 Code_JM. All rights reserved.
//

#import "Common.h"

#import <AFNetworking/AFNetworking.h>

#import "UIImageView+WebCache.h"

#import <Masonry.h>

#import <SystemConfiguration/SystemConfiguration.h>

#import "MBProgressHUD.h"

#import "LoginViewController.h"

static Common *sharedCommon = nil;

#define TimeoutInterval 20

NSString *const UUIDAccount = @"users";

 
@implementation Common
{
    DownloadFinishedBlock _finishedBlock;
    DownloadFailedBlock _failedBlock;
}
+ (Common *)shared{

    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        sharedCommon = [[Common alloc] init];
    });
    return sharedCommon;
}


///HTTP GET
+(void)requestWithUrlString:(NSString *)urlString
                contentType:(NSString *)type
                errorShow:(BOOL)errorShow
                   finished:(DownloadFinishedBlock)finishedBlock
                     failed:(DownloadFailedBlock)failedBlock{
    
    
    AFHTTPRequestOperationManager *manager  = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = TimeoutInterval;
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
  
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string     =  [user objectForKey:login_token];
     
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    if (string.length > 0)
    {
        [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
    }
    //NSLog(@"errorShow===>%hhd", errorShow);
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
 
        if (![responseObject[@"messageCode"] isEqual:[NSNull null]])
        {
            if (![responseObject[@"success"] boolValue] && [responseObject[@"messageCode"] isEqualToString:@"5004"])
            {
                
                UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:responseObject[@"message"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    //                    [user setObject:nil forKey:login_token];
                    
                    LoginViewController *loginVC = [[LoginViewController alloc]init];
                    UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                    
                    [viewC presentViewController:loginNC animated:YES completion:nil];
                    
                }];
                
                [alert addAction:action1];
                
#pragma mark push方法跟这一样，只是变变写法
                
                
            } else {
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                NSString *string = [user objectForKey:login_token];
                
                
                if (string.length > 0) {
                    
                    [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
                    
                }
            }
        }
        finishedBlock(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        if (errorShow != NO)
        {
             [Common showAlertViewAndAnimated:YES andString:@"系统维护中"];
        }
        else if ([error.localizedDescription isEqualToString:@"请求超时。"])
        {
            [Common showAlertViewAndAnimated:YES andString:error.localizedDescription];
        }
        failedBlock(error.localizedDescription);
    }];
}


///HTTP Post
+ (void)afPostRequestWithUrlString:(NSString *)urlString
                            parms:(NSDictionary *)dic
                    finishedBlock:(DownloadFinishedBlock)finished
                      failedBlock:(DownloadFailedBlock)failed{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //Content-Type 要写成与服务器相匹配的类型,一开始可以不写，error信息中会提示我们Content-Type要写成什么
    //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    //实现基本的post请求,函数的参数:为请求地址，和带有post请求参数的字典
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    manager.requestSerializer.timeoutInterval = TimeoutInterval;
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string = [user objectForKey:login_token];
    
    
    if (string.length > 0) {
        
        [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
        
    }
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    [manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //调用自己定义的block
        
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        if ([dictionary[@"messageCode"] isEqual:[NSNull null]]) {
            
            finished(responseObject);
            
        } else {
            
            
            if (![dictionary[@"success"] boolValue] && [dictionary[@"messageCode"] isEqualToString:@"5004"]) {
                
                UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:responseObject[@"message"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    //                [user setObject:nil forKey:login_token];
                    
                    
                    LoginViewController *loginVC = [[LoginViewController alloc]init];
                    UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                    
                    [viewC presentViewController:loginNC animated:YES completion:nil];
                    
                }];
                
                [alert addAction:action1];
                
            } else {
                
                finished(responseObject);
                
            }
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //当出现错误信息是 弹出提示框
        //        [Common showAlertViewAndAnimated:YES andString:error.localizedDescription];
        [Common showAlertViewAndAnimated:YES andString:@"系统维护中"];
        
        
        //捕捉错误信息
        failed(error.localizedDescription);
    }];
}

///HTTP Post
- (void)afPostRequestWithUrlString:(NSString *)urlString
                             parms:(NSDictionary *)dic
                     finishedBlock:(DownloadFinishedBlock)finished
                       failedBlock:(DownloadFailedBlock)failed{
    if (_finishedBlock!=finished) {
        _finishedBlock = nil;
        _finishedBlock = finished;
    }
    if (_failedBlock!=failed) {
        _failedBlock = nil;
        _failedBlock = failed;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //Content-Type 要写成与服务器相匹配的类型,一开始可以不写，error信息中会提示我们Content-Type要写成什么
    //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    //实现基本的post请求,函数的参数:为请求地址，和带有post请求参数的字典
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    manager.requestSerializer.timeoutInterval = TimeoutInterval;
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    //
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string = [user objectForKey:login_token];
    
    if (string.length > 0) {
        
        [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
        
    }
    
    
    [manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //调用自己定义的block
        
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        //NSLog(@"%@", dictionary);
        
        if ([dictionary[@"messageCode"] isEqual:[NSNull null]]) {
            
            finished(responseObject);
            
        } else {
            
            if (![dictionary[@"success"] boolValue] && [dictionary[@"messageCode"] isEqualToString:@"5004"]) {
                
                UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:responseObject[@"message"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    
                    //                [user setObject:nil forKey:login_token];
                    
                    
                    LoginViewController *loginVC = [[LoginViewController alloc]init];
                    UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                    
                    [viewC presentViewController:loginNC animated:YES completion:nil];
                    
                }];
                
                [alert addAction:action1];
                
            } else {
                
                finished(responseObject);
                
            }
            
        }
        
        //        _finishedBlock(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        //当出现错误信息是 弹出提示框
        //        [Common showAlertViewAndAnimated:YES andString:error.localizedDescription];
        [Common showAlertViewAndAnimated:YES andString:@"系统维护中"];
        
        
        //捕捉错误信息
        _failedBlock(error.localizedDescription);
    }];
}



///HTTP 上传图片
//dic 中放除图片以外的其他参数, data 图片转换的NSData key 为图片对应的key：pis
- (void)afUploadImageWithUrlString:(NSString *)urlString
                             parms:(NSDictionary *)dic
                         imageData:(NSData *)data
                          imageKey:(NSString *)key
                     finishedBlock:(DownloadFinishedBlock)finished
                       failedBlock:(DownloadFailedBlock)failed{
    if (_finishedBlock!=finished) {
        _finishedBlock = nil;
        _finishedBlock = finished;
    }
    if (_failedBlock!=failed) {
        _failedBlock = nil;
        _failedBlock = failed;
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    //上传图片的post方法
    [manager POST:urlString parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //利用formData 实现图片上传(可以类比ASI的setData......方法)
        //FileData 图片转换成的NSData
        //name 服务端规定的参数 pis
        //fileName  临时名称
        //mimeType data的文件类型
        [formData appendPartWithFileData:data name:key fileName:@"test.png" mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _finishedBlock(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        _failedBlock(error.localizedDescription);
    }];
}



///判断是否登录
+ (void)isLogin:(UIViewController *)target
        andPush:(UIViewController *)next{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *string = [userDefaults objectForKey:@"login"];
    
    //    self.isLogin =
    
    if (string == nil ) {
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        
        [target presentViewController:loginNC animated:YES completion:nil];
        
    }  else {
        [target.navigationController pushViewController:next animated:YES];
    }
}




///判断用户类型
+ (BOOL)judgeUsertype{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    NSString *string = [user objectForKey:@"userType"];
    
    if ([string isEqualToString:@"50"])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}



///创建一个消息提示框
+ (void)showAlertViewAndAnimated:(BOOL)animated
                       andString:(NSString *)string{
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    view.backgroundColor = [UIColor blackColor];
    [window addSubview:view];
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, window.frame.size.width/2.0, 20)];
    label.text = string;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:15];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    CGRect rect = [label.text boundingRectWithSize:CGSizeMake(window.frame.size.width/2.0, 200) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
    label.frame = CGRectMake(15, 5, rect.size.width + 20, rect.size.height + 10);
    view.frame = CGRectMake(0, 0, rect.size.width + 50, rect.size.height + 20);
    [view addSubview:label];
    view.layer.cornerRadius = 10;
    
    view.center = window.center;
    
    if (animated) {
        view.alpha = 0;
        [window addSubview:view];
        
        [UIView animateWithDuration:0.3 animations:^{
            view.alpha = 0.78;
        } completion:^(BOOL finished) {
            
            
        }];
    }
    else {
        [window addSubview:view];
    }
    
    //延迟执行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [view removeFromSuperview];
        
    });
    
}

//提示框
- (UIImageView*)createUIImage:(NSString *)title andDelay:(float)delay {
    
    UILabel * label =[[UILabel alloc]init];
    label.text = title;
    label.tag = 88;

    label.textAlignment = NSTextAlignmentCenter;
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:FontOfSize15];
    label.textColor = [UIColor whiteColor];
    CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    
    // 名字的H
    CGFloat nameH = size.height;
    // 名字的W
    CGFloat nameW = size.width;
    
    
    label.frame =CGRectMake(0, 0, nameW, nameH);
    label.font = Font(FontOfSize15);

    UIImageView * imageCollect = [[UIImageView alloc]init];
    imageCollect.image = [UIImage imageNamed:@"project_product_collect_jiaohu"];
    imageCollect.frame = CGRectMake(0, 0, 90+label.frame.size.width, 41);
    imageCollect.alpha = 0.5;
    imageCollect.tag = 100;
    
    
    [imageCollect addSubview:label];
    //收藏成功提示
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imageCollect.mas_centerX);
        make.centerY.equalTo(imageCollect.mas_centerY);
    }];
    
    [self performSelector:@selector(CollectDissMi:) withObject:imageCollect afterDelay:delay];
    

    return imageCollect;
}

- (void)CollectDissMi:(UIImageView *)sender{
    
    [sender  removeFromSuperview];
}


+ (float)contentBackWidthText:(NSString *)content
               fonts:(UIFont *)fonts
            maxWidth:(float)maxWidth
           maxHeight:(float)maxHeight {
    
    // CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    
    /**高度*/
    NSDictionary *attrbute = @{NSFontAttributeName:fonts};
    
    if (maxWidth <= 0)
    {
        maxWidth = (screenWidth - 14 * 2);
    }
    if (maxHeight <= 0)
    {
        maxHeight = 1000;
    }
    CGFloat text = [content boundingRectWithSize:CGSizeMake(maxWidth, maxHeight) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine attributes:attrbute context:nil].size.width;
    
    return text;
    
}
+ (float)contentText:(NSString *)content
                fonts:(UIFont *)fonts
            maxWidth:(float)maxWidth
           maxHeight:(float)maxHeight {
    
    // CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    
    /**高度*/
    NSDictionary *attrbute = @{NSFontAttributeName:fonts};
    
    if (maxWidth <= 0)
    {
        maxWidth = (screenWidth - 14 * 2);
    }
    if (maxHeight <= 0)
    {
        maxHeight = 1000;
    }
    CGFloat text = [content boundingRectWithSize:CGSizeMake(maxWidth, maxHeight) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine attributes:attrbute context:nil].size.height;
    
    return text;
    
}
- (float)contentText:(NSString *)content
                font:(NSUInteger)font
            maxWidth:(float)maxWidth
           maxHeight:(float)maxHeight {
    /**高度*/
    NSDictionary *attrbute = @{NSFontAttributeName:[UIFont systemFontOfSize:14.0f]};
    
    if (maxWidth <= 0)
    {
        maxWidth = (screenWidth - 14 * 2);
    }
    if (maxHeight <= 0)
    {
        maxHeight = 1000;
    }
    CGFloat text = [content boundingRectWithSize:CGSizeMake(maxWidth, maxHeight) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrbute context:nil].size.height;
    
    return text;
}



+ (UIAlertController *)sureAlertsControllerWithMessage:(NSString *)message
                                                action:(void (^)(UIAlertAction *action))handler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    NSMutableAttributedString *alertControllerStr = [[NSMutableAttributedString alloc] initWithString:@"提示"];
    
    [alertControllerStr addAttribute:NSForegroundColorAttributeName
                               value:[UIColor orangeColor]
                               range:NSMakeRange(0, 2)];
    
    [alert setValue:alertControllerStr forKey:@"attributedTitle"];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定"
                                                      style:UIAlertActionStyleDefault
                                                    handler:handler];
                              
                              
    [action1 setValue:[UIColor orangeColor] forKey:@"titleTextColor"];
    
    [alert addAction:action1];
    
    return alert;
    
}

+ (UIAlertController *)zj_QueueAlertsControllerWithMessage:(NSString *)message
                                             continueTitle:(NSString *)continueTitle
                                               cancelTitle:(NSString *)cancelTitle
                                                    cancelAction:(void (^)(UIAlertAction *action))handler {
    
    
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action = [UIAlertAction actionWithTitle:cancelTitle
                                                      style:0
                                                    handler:handler];

    UIAlertAction * action1 = [UIAlertAction actionWithTitle:continueTitle style:0 handler:nil];
    
    
    [alert addAction:action];
    
    [alert addAction:action1];

     return alert;
}
+ (UIAlertController *)zj_alertsControllerWithMessage:(NSString *)message
                                                     title:(NSString *)title
                                                  sureItem:(NSString *)sureItem
                                                sureAction:(void (^)(UIAlertAction *action))handler {
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:sureItem style:UIAlertActionStyleDefault  handler:handler];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    
    [alert addAction:action1];
    
    [alert addAction:action2];
    
    return alert;

    
}

@end
